# coding=utf8

from app import create_app
from app.modules.common.jsonFileUtil import getJsonFile
from app.extensions import db
from app.modules.common.utils import DbCommit
from app.modules.entrance.models import EntranceInfo
from app.modules.apps.models import AppInfo

application = create_app(flask_config = 'local')


def main(_env_name, _zone_code, _type, _tasks, _ahosts, _bhosts, _apps):
    with application.app_context():
        _entrance = EntranceInfo.query.filter_by(type = _type, env_name = _env_name, zone_code = _zone_code).first()

        for task in _tasks:
            if str(task).startswith(_type):
                _ip = str(task).split("//")[1].split(":")[0]
                _port = str(task).split("//")[1].split(":")[1]
                _group = None
                _app_name = None
                if _ip in _ahosts:
                    _group = "A"
                if _ip in _bhosts:
                    _group = "B"
                for app in _apps:
                    if app["port"] == _port:
                        _app_name = app["name"]
                        break
                if _type == "jmx":
                    _info = AppInfo(app_name = _app_name, host = _ip, jmx_port = _port, app_type = "java",
                                    entrance_id = _entrance.id, entrance_type = _type, current_status = "GNONE",
                                    expect_status = "GNONE", zone_code = _zone_code, group = _group,
                                    env_name = _env_name)
                elif _type == "hosts":
                    _info = AppInfo(app_name = _app_name, host = _ip, agent_port = _port, app_type = "php",
                                    entrance_id = _entrance.id, entrance_type = _type, current_status = "GNONE",
                                    expect_status = "GNONE", zone_code = _zone_code, group = _group,
                                    env_name = _env_name)
                print _info.to_dict()
                db.session.add(_info)
        DbCommit()


if __name__ == '__main__':
    _env_name = 'staging'
    _zone_code = 'uc.auaws.area'
    _type = "jmx"

    _json = getJsonFile("tasks.txt")

    _ahosts = _json['env']['ahosts']
    _bhosts = _json['env']['bhosts']
    _tasks = _json['tasks']

    file_object = open('apps.txt')
    _apps = []
    for line in file_object:
        line = str(line).replace("\n", "")
        _apps.append({"name": str(line).split(" ")[0], "port": str(line).split(" ")[1]})

    main(_env_name, _zone_code, _type, _tasks, _ahosts, _bhosts, _apps)
